<!--
 * @Author: liyin 2179253556@qq.com
 * @Date: 2022-11-11 15:02:16
 * @LastEditors: liyin 2179253556@qq.com
 * @LastEditTime: 2025-10-28 08:49:52
 * @FilePath: Index.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<template>
    <div class="user-info-box">
        <SearchComp @clear="clearHandle">
            <RowItem label="选择模块" :count="1">
                <el-select v-model="personQuery.module_id" filterable clearable @change="selectModule" style="width:100%;" placeholder="请选择模块">
                    <el-option v-for="(item, index) in moduleType" :key="index" :label="item.name" :value="item.uuid">
                    </el-option>
                </el-select>
            </RowItem>
            <RowItem label="选择分类" :count="2">
                <el-cascader ref="cascader" v-model="category_ids" :options="typeTree" :props="{
                    checkStrictly: true,
                    value: 'id',
                    label: 'name',
                    children: 'child',
                }" style="width:100%;" @change="selectCategory" placeholder="请选择分类" clearable />
            </RowItem>
            <RowItem label="关键字" :count="3">
                <el-input clearable placeholder="请输入文章标题/内容关键字搜索" v-model="personQuery.search" prefix-icon="Search"
                    class="input-with-select" @input="Search">
                </el-input>
            </RowItem>
        </SearchComp>
        <Table :data="tableData" :config="tableConfig" @handleEdit="handleEdit" :total="total" @sizeChange="sizeChange"
            @CurrentChange="CurrentChange" :showLoading="showLoading">
            <el-button type="primary" @click="Add">发布文章</el-button>
            <!-- <el-button type="primary" plain class="white-bg-btn">一键审核</el-button> -->
            <el-button v-if="markType!='site_home'" type="primary" plain class="white-bg-btn" @click="addType">分类编辑</el-button>
        </Table>
        <!-- 添加数据和添加文章模块 -->
        <el-drawer v-model="editFormVisible" direction="rtl" :close-on-click-modal="false" class="editDrawer">
            <template #header>
                <div>{{ isPreviewBol ? '预览文章' : editId ? '编辑数据' : '添加数据' }}</div>
                <el-button type="primary" plain class="white-bg-btn" v-if="!isPreviewBol" @click="modelCancel3">关 闭
                </el-button>
                <el-button type="primary" plain class="white-bg-btn" v-if="isPreviewBol"
                    @click="RemotePlayback">返回设置</el-button>
            </template>
            <EdtiArticle ref="editRef" :editFormVisible="editFormVisible" :dataItem="dataItem" :editId="editId"
                :isPreviewBol="isPreviewBol" :moduleType="moduleType" @getList="getList" @setModuleId="setModuleId" @modelCancel="modelCancel"
                @changePreviewStaus="changePreviewStaus"></EdtiArticle>
        </el-drawer>
        <!-- 新增分类 -->
        <Model title="分类编辑" :modelShow="addDialogVisible" width="40" :btnShow="false"
            @cancel="addDialogVisible = false">
            <div class="score-add-flex">
                <div class="row" style="align-items: center; padding:0 15px;">
                    <span>选择模块</span>
                    <el-select v-model="editModuleId" filterable @change="selectModule2" style="flex:1;margin:0 15px;" placeholder="请选择模块">
                        <el-option v-for="(item, index) in moduleType" :key="index" :label="item.name" :value="item.uuid">
                        </el-option>
                    </el-select>
                    <el-button type="primary" plain class="white-bg-btn" :disabled="!editModuleId" @click="addItem">
                        <el-icon size="16">
                            <CirclePlusFilled />
                        </el-icon>&nbsp;&nbsp;新增分类
                    </el-button>
                </div>
                <el-row style="margin: 20px 0 10px 0;">
                    <el-col :span="10" style="padding-left:30px;margin-right: 0;">分类名称</el-col>
                    <el-col :span="8" style="padding-left:20px;margin-right: 0;text-align: center;">是否显示</el-col>
                    <el-col :span="6" style="padding-left:20px;text-align: center;">操作</el-col>
                </el-row>
               <div style="padding-right:20px;margin-left: -5px;">
                    <AddChildren :dataItem="dataItem" :checkIndex="checkIndex" @getTreeList="getTreeList"
                        @forData2="forData2" @setDate="setDate" :module_id="personQuery.module_id">
                    </AddChildren>
                    <el-empty v-if="dataItem.length == 0" description="暂无分类" />
               </div>
            </div>
        </Model>
        <!-- 文章查看和预览 -->
        <el-drawer v-model="detailDialogVisible" title="查看详情" direction="rtl" :close-on-click-modal="false">
            <DetaileModule :detailDialogVisible="detailDialogVisible" :isPreview="isPreview" :editInfo="editInfo"
                @modelCancel="modelCancel2">
            </DetaileModule>
        </el-drawer>
    </div>
</template>
<script setup lang="ts">
import { ref, h, onMounted, reactive, nextTick, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
// 引入专属的request配置
import { newsCategory, newsList, delNews, detailNews, downNews, upNews, moduleList } from '../../Api/Publish'
import EdtiArticle from './EdtiArticle.vue'
import AddChildren from './AddChildren.vue'
import DetaileModule from './DetaileModule.vue'
import { PiniaStore } from '../../../store'
import $util from '../../../util/util'
import { mapValues } from 'lodash'
const store = PiniaStore()
const markType = ref<string>('')
const markName = ref<string>('')
const category_ids = ref<any>([])
const personQuery = reactive({
    search: '',
    module_id: '',
    category_id: '',
    page: 1,
    page_size: store.pageQuery.page_size,
})
const editFormVisible = ref(false)
const editRef = ref<any>(null)
const modelCancel = () => {
    editFormVisible.value = false
}
const modelCancel3 = () => {
    if(editRef.value.isShowPrograss){
        return ElMessage.error('正在上传中附件，不能关闭!')
    }
    editRef.value.reactCancel(editRef.value.editFormRef)
    editFormVisible.value = false
}
const RemotePlayback = () => {
    isPreviewBol.value = false
}
// 编辑文章的时候查看是否地预览状态
const isPreviewBol = ref<boolean>(false)
const changePreviewStaus = (bol: boolean) => {
    isPreviewBol.value = bol
}
// 文章查看和预览
const isPreview = ref<boolean>(false)
const detailDialogVisible = ref(false)
const modelCancel2 = () => {
    detailDialogVisible.value = false
}
// 编辑分类模块
const addDialogVisible = ref<boolean>(false)
// 编辑分类的模块id
const editModuleId = ref<string>('')
// 新增分类
const typeTree= ref<any>([])
const dataItem = ref<any>([])
const checkIndex = ref('')
const addItem = () => {
    dataItem.value.push({
        name: '',
        pid: 0,
        isSelect: true,
        level: 1,
        status: 1,
        child: []
    })
}
const setDate = (val: any) => {
    console.log(val)
    recursion(dataItem.value, val)
    dataItem.value = JSON.parse(JSON.stringify(dataItem.value))
}
// 递归找找
const recursion = (data: any, id: any) => {
    if (!data) {
        return;
    }
    if (!id) {
        return ElMessage.error('请先添加父级')
    }
    for (var i = 0; i < data.length; i++) {
        let item = data[i];
        if (item.id === id) {
            if (!item.hasOwnProperty('child')) {
                item.child = []
            }
            item.child.unshift({
                name: '',
                pid: item.id,
                isSelect: true,
                status: 1,
                level: Number(item.level) + 1,
            })
            break;
        } else if (item.child && item.child.length > 0) {
            recursion(item.child, id)
        }
    }
}
// 递归查找是否又没保存的
const forData2 = () => {
    var num = 0
    for (var i = 0; i < dataItem.value.length; i++) {
        if (dataItem.value[i].isSelect) {
            num++
        }
        if (dataItem.value[i].child && dataItem.value[i].child.length > 0) {
            for (var j = 0; j < dataItem.value[i].child.length; j++) {
                if (dataItem.value[i].child[j].isSelect) {
                    num++
                }
            }
        }
    }
    console.log(num, '数量')
    return num
}
// 点击清空条件触发
const clearHandle = () => {
    personQuery.search = ''
    personQuery.page = 1
    getList()
}
// 表格数据
const showLoading = ref<boolean>(false)
const total = ref(0)
const tableData = ref<any>([])
const tableConfig = ref([
    { name: 'index', label: '序号', width: '60', type: 'index', checked: true },
    { name: 'title', label: '文章名称', type: 'change', width: '220', checked: true },
    // { name: 'module_name', label: '所属模块', type: 'change', width: '140', checked: true },
    { name: 'category_path', label: '所属分类', type: 'change', width: '220', checked: true },
    {
        name: 'is_top',
        label: '是否置顶',
        width: '100',
        checked: true,
        type: 'status',
        formatter: [
            { name: 0, label: '否', status: 'default' },
            { name: 1, label: '是', status: 'success' }
        ]
    },
    { name: 'tags', label: '文章标签', type: 'label', width: '180', checked: true },
    {
        name: 'up_down',
        label: '发布状态',
        width: '100',
        checked: true,
        type: 'status',
        formatter: [
            { name: 0, label: '未发布', status: 'default' },
            { name: 1, label: '已发布', status: 'success' }
        ]
    },
    {
        name: 'allow_download',
        label: '允许下载',
        width: '100',
        checked: true,
        type: 'status',
        formatter: [
            { name: 0, label: '否', status: 'default' },
            { name: 1, label: '是', status: 'success' }
        ]
    },
    { name: 'creator_name', label: '创建人', type: 'change', width: '120', checked: true },
    { name: 'publisher_name', label: '发布者', type: 'change', width: '120', checked: true },
    { name: 'editor_name', label: '编辑人', type: 'change', width: '120', checked: true },
    // { name: 'create_date', label: '创建时间', type: 'change', width: '180', checked: true },
    { name: 'publish_date', label: '发布时间', type: 'change', width: '180', checked: true },
    { name: 'show_time', label: '上线时间', type: 'change', width: '180', checked: true },
    { name: 'expire', label: '过期时间', type: 'change', width: '180', checked: true },
    // { name: 'edit_date', label: '更新时间', type: 'change', width: '180', checked: true },
    {
        name: '',
        label: '操作',
        width: '200',
        fixed: 'right',
        type: 'edit',
        checked: true,
        limit: 4,
        formatter: [
            {
                name: 'releases', label: [{
                    value: '0',
                    name: '发布'
                }, {
                    value: '1',
                    name: '停用'
                }], value: 'up_down', isArry: true, key: 'disabled', font: true, link: true
            },
            { name: 'edit', label: '编辑', font: true, show: true, link: true, key: 'show' },
            { name: 'detail', label: '详情', font: true, show: true, link: true, key: 'show' },
            { name: 'delete', label: '删除', font: true, show: true, link: true, key: 'show' }
            // { name: 'preview', label: '预览', icon: 'icon_ic_eye', font: true, show: true, link: true, key: 'show' },
            // { name: 'delete', label: '删除', icon: 'icon_ic_delete_line', font: true, show: true, link: true, key: 'show' },
        ]
    }
])
const setModuleId=async (val:any)=>{
    personQuery.module_id = val
    personQuery.page = 1
}
// 获取权限列表
const getList = async () => {
    showLoading.value = true
    const res: any = await newsList(personQuery)
    if (res.code !== 1) {
        showLoading.value = false
        return ElMessage.error(res.msg)
    }
    tableData.value = res.data.list
    total.value = res.data.total
    showLoading.value = false
}
const Search = async () => {
    personQuery.page = 1
    getList()
}
const selectCategory = (val: any) => {
    if (val && val.length > 0) {
        personQuery.category_id = val[val.length - 1]
    } else {
        personQuery.category_id = ''
    }
    Search()
}
// 点击添加角色
const Add = async () => {
    editId.value = ''
    editFormVisible.value = true
}
// 点击设置菜单权限
const editId = ref<string>('')
const editInfo = ref<any>({})
const handleEdit = async (item: any, name: string) => {
    if (name === 'edit') {
        // 编辑
        editId.value = item.uuid
        editFormVisible.value = true
    } else if (name === 'detail') {
        const res: any = await detailNews({ id: item.uuid })
        if (res.code !== 1) return ElMessage.error(res.msg)
        editInfo.value = res.data
        detailDialogVisible.value = true
    } else if (name === 'delete') {
        // 删除（修复后代码）
        ElMessageBox({
            title: '温馨提示',
            message: h('p', { style: 'font-weight:bold;font-size: 15px;color: #333333;' }, [
                h('span', null, '确定要删除？'),
                h('p', { style: 'font-size: 14px;font-weight:normal;color: rgba(0,0,0,0.65);margin-top:10px;' }, '删除后将无法恢复，确定要继续吗?'),
            ]),
            showCancelButton: true,
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
            beforeClose: async (action, instance, done) => {
                if (action === 'confirm') {
                    const res: any = await delNews({ id: item.uuid })
                    if (res.code !== 1) {
                        done()
                        return ElMessage.error(res.msg)
                    }
                    ElMessage.success(res.msg)
                    getList()
                    done()
                } else {
                    done() // 取消时正常关闭弹框
                }
            }
        }).then((action) => {
            // 确认操作已在 beforeClose 中处理
        }).catch((err) => {
            // 捕获取消操作的拒绝状态（err 为 'cancel'）
            if (err === 'cancel') {
                // 可选：添加取消提示（根据需求）
                // ElMessage.info('已取消删除')
            }
        })
    } else if (name === 'preview') {
        // 预览文章
        isPreview.value = true
        const res: any = await detailNews({ id: item.uuid })
        if (res.code !== 1) return ElMessage.error(res.msg)
        editInfo.value = res.data
        detailDialogVisible.value = true
    } else if (name === 'releases') {
        // 发布和停用
        ElMessageBox({
            title: '温馨提示',
            message: h('p', { style: 'font-weight:bold;font-size: 15px;color: #333333;' }, [
                h('span', null, Number(item.up_down) === 0 ? `确定要发布该条文章？` : '停用文章后将不在前台页面展示，确定要停用吗？'),
            ]),
            showCancelButton: true,
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
            beforeClose: async (action, instance, done) => {
                if (action === 'confirm') {
                    const params: any = {
                        id: item.uuid
                    }
                    const res: any = Number(item.up_down) === 0 ? await upNews(params) : await downNews(params)
                    if (res.code !== 1) {
                        done()
                        return ElMessage.error(res.msg)
                    }
                    ElMessage.success(res.msg)
                    getList()
                    done()
                } else {
                    done()
                }
            },
        }).then((action) => {
        })
    }
}
// 点击翻页器的长度
const sizeChange = () => {
    personQuery.page_size = store.pageQuery.page_size
    getList()
}
// 点击翻页器的页码
const CurrentChange = () => {
    personQuery.page = store.pageQuery.page
    getList()
}
// 获取学校列表
const schoolList = ref<any>([])
watch(
    () => addDialogVisible.value,
    (newValue, oldValue) => {
        // 获取文章详情
        if (!addDialogVisible.value) {
            // 递归初始化数据
            dataItem.value.forEach((node: any) => $util.removeNodesWithoutId(node)); // 对每个顶级节点应用函数
        }
    },
    { deep: true, immediate: true }
)
const moduleType = ref<any>([])
const getModuleList = async () => {
    const res: any = await moduleList()
    if (res.code !== 1) return ElMessage.error(res.msg)
    moduleType.value = res.data
    if (moduleType.value.length > 0) {
        editModuleId.value = moduleType.value[0].uuid
    }
    if(moduleType.value.length === 1){
        personQuery.module_id = moduleType.value[0].uuid
    }
}
const selectModule = async (val: any) => {
    category_ids.value=[]
    personQuery.category_id=''
    if(val){
        await getTreeList(1)
    }
    Search()
}
// 分类编辑
const addType = async() => {
    addDialogVisible.value = true
    if(personQuery.module_id){
        editModuleId.value = personQuery.module_id
    }
    if(editModuleId.value){
        await getTreeList(2)
    }
}
//  获取分类
const getTreeList = async (val:number) => {
    const params = {
        module_id: val === 1?personQuery.module_id:editModuleId.value,
    }
    const res: any = await newsCategory(params)
    if (res.code !== 1) return ElMessage.error(res.msg)
    if(val === 1){
        typeTree.value = res.data
    } else{
        dataItem.value = JSON.parse(JSON.stringify(res.data))
    }
    
}
const selectModule2 = async (val: any) => {
    await getTreeList(2)
}
onMounted(async () => {
    await getModuleList()
    await getList()
})
</script>
<style lang="scss" scoped>
:deep(.el-dialog) {
    width: 768px;
}

:deep(.el-drawer) {
    width: 70% !important;
    min-width: 1060px !important;

    .el-drawer__wrapper {
        overflow: hidden;
    }
}

:deep(.el-drawer.editDrawer) {
    .el-drawer__close {
        display: none;
    }

    .el-drawer__header {
        padding: 10px 15px !important;
    }
}
</style>
